//
//  CunLiShiManagerViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/7/22.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "CunLiShiManagerViewController.h"
#import "Config.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "CunLiShi.h"
#import "UIImageView+WebCache.h"
#import "TongZhi.h"
#import "NewDetailController.h"
#import "TongZhiDetailViewController.h"
#import "MJRefresh.h"
#import "PublishThingsViewController.h"
#import "PublishTongZhiViewController.h"

@interface CunLiShiManagerViewController (){
    
    NSMutableArray *cunLiShiArray;
    float screenWidth,screenHeight;
    NSString *urlString;
    int contentPage;
    
}

@end

@implementation CunLiShiManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    contentPage=1;
    screenWidth=[UIScreen mainScreen].bounds.size.width;
    screenHeight=[UIScreen mainScreen].bounds.size.height;
    cunLiShiArray=[[NSMutableArray alloc]init];
    self.cunLiShiTableView.rowHeight=70;
    
    if (self.type==1) {
        self.title=@"村里事管理";
        self.cunLiShiTableView.rowHeight=70;
    }else{
        self.title=@"通知通告管理";
        self.cunLiShiTableView.rowHeight=60;
    }
    self.view.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(writeCunLiShi) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
    
    [self getCunLiShiWithBool:YES];
    [self addRefreshAttribute];
    
    if ([self.cunLiShiTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.cunLiShiTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.cunLiShiTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.cunLiShiTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    [self.cunLiShiTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    [self.cunLiShiTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
}

- (void)reloadDataToNew:(BOOL)new{
    
    if (new) {
        contentPage=1;
        [self getCunLiShiWithBool:YES];
    }else{
        contentPage=contentPage+1;
        [self getCunLiShiWithBool:NO];
    }
}

-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)writeCunLiShi{
    
    if (self.type==2) {
        PublishTongZhiViewController *publishVC=[[PublishTongZhiViewController alloc]init];
        [self.navigationController pushViewController:publishVC animated:YES];
        return;
    }
    PublishThingsViewController *publishVC=[[PublishThingsViewController alloc]init];
    [self.navigationController pushViewController:publishVC animated:YES];
}

-(void)getCunLiShiWithBool:(BOOL)isRefresh{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",contentPage] forKey:@"page"];
    [CheckParams setObject:@"10" forKey:@"pagesize"];
    if (self.type==1) {
        urlString=@"op_newslist.php";
    }else{
        urlString=@"op_noticlist.php";
    }
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:urlString httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        [self.cunLiShiTableView.legendHeader endRefreshing];
        [self.cunLiShiTableView.legendFooter endRefreshing];
        
        NSArray *listArray;
        if (self.type==1) {
            
            if (![[result objectForKey:@"response"] isEqualToString:@"op_newslist"]) {
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
                hud.labelText = @"获取详情失败!";
                [hud hide:YES afterDelay:1];
                return ;
            }
            NSDictionary *dataDic=[result objectForKey:@"newslist"];
            listArray=[dataDic objectForKey:@"list"];
            
        }else{
            
            if (![[result objectForKey:@"response"] isEqualToString:@"op_noticlist"]) {
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
                hud.labelText = @"获取详情失败!";
                [hud hide:YES afterDelay:1];
                return ;
            }
            listArray=[result objectForKey:@"list"];
        }
        
        if (listArray.count==0) {
            
            if (!isRefresh) {
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
                hud.labelText = @"没有更多数据";
                [hud hide:YES afterDelay:1];
                contentPage=contentPage-1;
            }
            [self.cunLiShiTableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            return ;
        }
        
        if (isRefresh) {
            [cunLiShiArray removeAllObjects];
        }
        
        if (self.type==1) {
            for (NSDictionary *dic in listArray) {
                //CunLiShi *cunLi=[[CunLiShi alloc]initWithDictionary:dic];
                CunLiShi *cunLi=[CunLiShi yy_modelWithDictionary:dic];
                [cunLiShiArray addObject:cunLi];
            }
        }else{
            for (NSDictionary *dic in listArray) {
                //TongZhi *tongZhi=[[TongZhi alloc]initWithDictionary:dic];
                TongZhi *tongZhi=[TongZhi yy_modelWithDictionary:dic];
                [cunLiShiArray addObject:tongZhi];
            }
        }
        [self.cunLiShiTableView reloadData];
        
    }failureAction:^{
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return cunLiShiArray.count;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *cellIdentifier=@"cell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if(!cell){
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if (self.type==1) {
        
        CunLiShi *cunli=[cunLiShiArray objectAtIndex:indexPath.row];
        UIImageView *picImgView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 5, 80, 60)];
        picImgView.contentMode = UIViewContentModeScaleAspectFill;
        picImgView.clipsToBounds = YES;
        [picImgView setImageWithURL:[NSURL URLWithString:cunli.pic] placeholderImage:[UIImage imageNamed:@"phoneplace.png"]];
        [cell addSubview:picImgView];
        
        UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(100, 10, screenWidth-100, 20)];
        titleLabel.text=cunli.title;
        [cell addSubview:titleLabel];
    }else{
        
        TongZhi *tongZhi=[cunLiShiArray objectAtIndex:indexPath.row];
        UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(60, 10, screenWidth-70, 22)];
        titleLab.numberOfLines=0;
        titleLab.text=tongZhi.title;
        [cell addSubview:titleLab];
        
        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 43, 22)];
        if (tongZhi.type==1) {
            img.image=[UIImage imageNamed:@"tongzhi.png"];
        }else{
            img.image=[UIImage imageNamed:@"tonggao.png"];
        }
        [cell addSubview:img];
        
        UILabel *timeLabel=[[UILabel alloc]initWithFrame:CGRectMake(screenWidth-290, 40,280, 15)];
        timeLabel.text=tongZhi.addtime;
        timeLabel.textAlignment=2;
        timeLabel.font=[UIFont systemFontOfSize:14];
        timeLabel.textColor=[UIColor grayColor];
        [cell addSubview:timeLabel];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.type==1) {
        CunLiShi *cunli=[cunLiShiArray objectAtIndex:indexPath.row];
        NewDetailController *newVC=[[NewDetailController alloc]init];
        newVC.itemID=cunli.itemid;
        [self.navigationController pushViewController:newVC animated:YES];
    }else{
        TongZhi *tongZhi=[cunLiShiArray objectAtIndex:indexPath.row];
        TongZhiDetailViewController *tongZhiVC=[[TongZhiDetailViewController alloc]init];
        tongZhiVC.itemid=tongZhi.itemid;
        tongZhiVC.type=tongZhi.type;
        [self.navigationController pushViewController:tongZhiVC animated:YES];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //删除村里事管理或通知通告
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    
    if (self.type==1) {
        CunLiShi *cunli=[cunLiShiArray objectAtIndex:indexPath.row];
        [CheckParams setObject:cunli.itemid forKey:@"itemid"];
        [CheckParams setObject:@"1" forKey:@"type"];
    }else{
        TongZhi *tongZhi=[cunLiShiArray objectAtIndex:indexPath.row];
        [CheckParams setObject:[NSString stringWithFormat:@"%d",tongZhi.itemid] forKey:@"itemid"];
        [CheckParams setObject:@"3" forKey:@"type"];
    }
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"del_article.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        //NSLog(@"%@",result);
        NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
        if (str) {
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"删除失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }else{
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"删除成功!";
            [hud hide:YES afterDelay:1];
        }
        
        [cunLiShiArray removeAllObjects];
        [self.cunLiShiTableView reloadData];
        contentPage=1;
        [self getCunLiShiWithBool:YES];
        
    }failureAction:^{
        
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
